package com.traffic.api.restful;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;

import org.codehaus.jettison.json.JSONObject;

import com.gxhl.api.core.model.GDPResponse;
import com.gxhl.api.core.tools.JerseyClient;
import com.sun.jersey.api.client.ClientResponse;
import com.traffic.api.config.ApiProperties;
import com.traffic.api.exception.ApiBizException;

@Path("/{v}/phone")
public class PhoneRestful extends CheckRestful {
	private static final String HOST_PATH = ApiProperties.FLOW_HOST + "rest/1.0/phone";
//	private static final String PRAM_PHONE_NO = "phoneNo";

	@POST
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public GDPResponse phoneMsg(JSONObject param, @PathParam("v") String v) {
		GDPResponse result = new GDPResponse();
		try {
			Map<String, Object> params = check(param,"status");
			String phoneNo = (String) params.get("phoneNo");
			if ((phoneNo == null) || ("".equals(phoneNo))) {
				result.setCode("0001");
				result.setMsg("手机号码不能为空");
				return result;
			}
			if (isMobileNO(phoneNo)) {
				result.setCode("0001");
				result.setMsg("手机号码不正确");
				return result;
			}

			ClientResponse response = JerseyClient.getInstance().post(HOST_PATH, param);

			if (response.getStatus() == 500) {
				result.setCode("0001");
				result.setMsg("系统异常:查询号码信息异常 ：" + response.getStatus());
				return result;
			}
			if (response.getStatus() != 200) {
				result.setCode("0001");
				result.setMsg("系统异常:查询号码信息异常 ：" + response.getStatus());
				return result;
			}
			if (response.getStatus() == 200) {
				result.setCode("0000");
			}

			GDPResponse output = (GDPResponse) response.getEntity(GDPResponse.class);
			result.setMsg(output.getMsg());
			result.setData(output.getData());
		} catch (ApiBizException e) {
			result.setCode("0001");
			result.setMsg(e.getCause().getMessage());
		} catch (WebApplicationException e) {
			result.setCode("0001");
			result.setMsg(e.getCause().getMessage());
		} catch (Exception e) {
			result.setCode("0001");
			result.setMsg("系统异常:查询用户信息异常 ：" + e.getMessage());
			e.printStackTrace();
		}

		return result;
	}

	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9])|(17[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return (!(m.matches()));
	}
}